//David li 20100105
//SecurityResearch
var QS_SecurityResearch = function(){
    this.containerId = null;
    this.container = null;
    this.id = null;
    this.profile = null;
    this.el = null;
    this.ticker = '';
    this.secType = '';
    this.performanceId = '';
    this.tValidation = {};
    this.width = 0;
    this.widthCol1 = 0;
    this.widthCol2 = 0;
    this.height = 0;
    this.loadingCount = 0;
    this.coll = null;
    this.colr = null;
    this.box1 = null;
    this.box2 = null;
    this.box3 = null;
    this.box4 = null;
    this.box3CpnList = [10, 6, 7];
    this.moreBtns = null;
    this.HTML = '<div class="rtq-sr"><div class="container clearfix">'
                +'<div class="l-col"><div class="box b1"><a class="rtq-sr-more" href="#" type="1">more...</a></div><div class="box b2"><a class="rtq-sr-more" href="#" type="3">more...</a></div></div>'
                +'<div class="r-col"><div class="box b3"><a class="rtq-sr-more" href="#" type="10">more...</a></div><div class="box b4"><a class="rtq-sr-more" href="#" type="2">more...</a></div></div>'
                +'</div></div>';
    this.objectPath = "";
    this.settingPanel = null;
    this.box3Tab = null;
    this.emptyComponent = function(){
        this.changeOutSize = function(){};
        this.acceptTicker = function(){};
        this.saveConfig = function(){};
        this.getTitle = function(){};
        this.isInit = false
    };
    this.settingPnMap = {
        1: 'rtq-window-setpn-cht',
        2: 'rtq-window-setpn-sr-news' 
    };
    this.cpns = {}; //components
    this.cpnConfig = null;
    this.i=0;
};
QS_SecurityResearch.prototype = {
    init: function(ContainerId, Profile, Sid){
        var self = this;
        this.containerId = ContainerId;
        this.container = $('#' + ContainerId);
        this.id = Sid;
        this.objectPath = "push.proxy.getSR(" + this.id + ")";
        this.profile = Profile;
        this.cpnConfig = this.profile.cpnConfig || {};
        this.el = $(this.HTML).css({
            height: this.container.parent().height()
        });
        
        this.el.appendTo(this.container);
        if(this.hasSearch){
            this.initAutoComplete();
        }
        
        this.createSettingPN();
        
        this.coll = this.el.find('.l-col');
        this.colr = this.el.find('.r-col');
        this.width = (this.container.parent().width()||400) - 10;
        this.height = this.container.parent().height()||400;
        this.widthCol1 = this.width < 900 ? this.width * 0.5 : this.width - 450;//this.width*0.6;
        this.widthCol2 = this.width < 900 ? this.width * 0.5 : 450;//this.width*0.4;
        this.box1 = this.el.find('.b1');
        this.box2 = this.el.find('.b2');
        this.box3 = this.el.find('.b3');
        this.box4 = this.el.find('.b4');


        //box1 components - chart
        this._AddComponent({
            width: this.widthCol1,
            height: this._getBoxHeight(1),
            simpleMenu:true
        },1, this.box1);

        //box2 components - qt
        this._AddComponent({
            width: this.widthCol1,
            height: this._getBoxHeight(2),
            detail: false
        }, 3, this.box2);

        //box4 components - news
        this._AddComponent({
            Ticker: this.ticker,
            width: this.widthCol2,
            height: 200,
			plusSymbol:false,
            isShowContent: false,
            collapseable :false
        },2, this.box4);
            
        //event
        this.box2.find('.rtq-quicktake .rtq-qt-more').click(function(e){
            e.preventDefault();
            self._openCpnInWindow(3);
        });
        this.moreBtns = this.el.find('.rtq-sr-more').click(function(e){
            e.preventDefault();
            self._openCpnInWindow($(this).attr('type'));
        });
        if(typeof(QS_Detaching)!="undefined"&&QS_Detaching){ //hide more button in Detached window
            this.moreBtns.hide();
            this.box2.find('.rtq-quicktake .rtq-qt-more').hide();
        }
        this.moreBtns.eq(3).appendTo(this.box4.children('.ctn'));
        
        for (var i = 0; i < this.box3CpnList.length; i++) {
            this.cpns[this.box3CpnList[i]] = new this.emptyComponent();
        }
        this._createBox3('ST');
        
        if(Profile.ticker!=''){
            this.addTicker(Profile.ticker);
        }
    },
    _createBox3: function(SecType){
        for (var i = 0; i < this.box3CpnList.length; i++) {
            var cpn = this.cpns[this.box3CpnList[i]];
            if (cpn && cpn.isInit) {
                //remove component
                push.proxy.unregister(cpn);
                cpn.clear();
                delete this.cpns[this.box3CpnList[i]];
                this.cpns[this.box3CpnList[i]] = new this.emptyComponent();
            }
        }
        //box3 components - tabs
        var self = this;
        if (!this.box3Tab) {
            this.box3Tab = new Util.TabMenu(this.box3, this._getBox3CpnData(SecType), {
                onActive: function(tab){
                    self.moreBtns.eq(2).attr('type', tab.id);
                    var type = tab.id
                    if (!self.cpns[type].isInit) {
                        self._AddComponent({
                            ticker: self.ticker
                        }, type, tab.panel);
                        self.cpns[type].isInit = true;
                    }
                    if (type != 10) {
                        self._changeCpnOutSize(type);
                    }
                }
            }, {
                width: 80
            });
        }else{
            this.box3Tab.reBindData(this._getBox3CpnData(SecType));
        }
        this.box3Tab.setPanelOutSize('100%', this._getBoxHeight(3));
    },
    _getBox3CpnData:function(SecType){
        var box3CpnIDs = QS_SMC.getModuleConfig(SecType, this.box3CpnList);
        var box3CpnData = [];
        if (box3CpnIDs) {
            for (var i = 0; i < box3CpnIDs.length; i++) {
                box3CpnData.push({
                    txt: getDefaultProfileByType(box3CpnIDs[i]).name,
                    id: box3CpnIDs[i],
                    closable: false
                });
            }
            this.moreBtns.eq(2).show();
        }else{
            this.moreBtns.eq(2).hide();
        }
        return box3CpnData;
    },
    createSettingPN: function(){
        var self = this;
        
        this.settingPanel = $(this.settingPanel);
        var spStr = '<div class="til">Lock</div><div class="lock"></div>';
        for (var i in this.settingPnMap) {
            spStr += '<div class="' + this.settingPnMap[i] + '"></div>';
        }
        this.settingPanel.append(spStr);
        
        this.chkLock = new Util.ButtonGroup(this.settingPanel.find('.lock'), [{txt:'Lock window on symbol double-click',val:'lock'}], {
            onClick: function(v, btn){
                self.lock = btn.isSelected;
            }
        },{type:'checkbox'});
        this.chkLock.el[0].title = 'This function allows you to prevent the window from updating when you double-click a security in the watchlist.';
        if(this.profile.lock === true){
            self.lock = true;
            this.chkLock.btns['lock'].select();
        }
    },
    _AddComponent:function(cfg, type, box, hasContainer){
        if (!QSPC.checkPermission(type)) {
            box.html('<div style="padding:20px;">' + getDefaultProfileByType(type).name + " is not available in your account. If interested, please contact Morningstar.</div>");
            return null;
        }
        var self = this;
        var _id = idService.newMinusId();
        var _cid = idService.newId();
        if (!hasContainer) {
            box.append('<div id="' + _cid + '" class="ctn">');
        }
        var winObj = {
            settingPanelObj: {
                getSettingPNctn: function(){
                    return self.settingPanel.children('.' + self.settingPnMap[type]);
                },
                addtoSettingPN: function(){
                    return;
                },
                addClassToSettingPN: function(){
                    return;
                }
            },
            toolPanel: this.__winObj.toolPanel,
            contentMask:$('<div class="rtq-win-bd-mask"></div>').appendTo(box),
            contentEl:box,
            widget:this
        };
        cfg.securityType = this.profile.securityType;
        if(type == 1&&cfg&&cfg.height)cfg.height = cfg.height+26; // add the title height.
        if(type == 10){// for Quote init, we must set the width and height
            cfg=cfg?cfg:{};
            cfg.height=(cfg.height>0?cfg.height:this._getBoxHeight(3))+27;
            cfg.width=cfg.width>0?cfg.width:this.widthCol2;
        }
        this.cpns[type] = RtqDesktop._widgetClass[type](winObj, $.extend(cfg, this.cpnConfig[type]), _id, _cid, {
            type: type,
            id: _id,
            __winObj: winObj,
            elId: _id,
            containerId: _cid,
            hasSearch:false,
            //__ObjPath: this.objectPath + '.cpns[' + type + ']',
            setTitle: function(til){
                return;
            },
            getTitle: function(){
                return 'Security Research';
            },          
            showLoading: function(needToBeMasked){
                self.loadingCount++;
                if(self.loadingCount>4){self.loadingCount=4}
                self.showLoading();
                if(typeof needToBeMasked!='undefined'&&needToBeMasked!='undefined'&&needToBeMasked==true){
                    winObj.contentMask.show();
                } 
                self.__winObj.el.addClass('rtq-win-onloading');
            },
            hideLoading: function(){
                self.loadingCount--;
                if(self.loadingCount<0){self.loadingCount=0}
                if(self.loadingCount==0){
                    self.hideLoading();
                    self.__winObj.el.removeClass('rtq-win-onloading');
                }               
                winObj.contentMask.hide();                  
            },
            setWindowSize: function(w, h){
                return;
            }
        });
    },
    _getBoxHeight:function(boxIndex){
        var offsetPadding = 4;
        switch(boxIndex){
            case 1:{
                return (this.height- offsetPadding) * 0.5;
            }break;
            case 2:{
                return (this.height- offsetPadding) * 0.5;
            }break;
            case 3:{
                return (this.height- offsetPadding) * 0.45 - 28; //cut tab height
            }break;
            case 4:{
                return (this.height- offsetPadding) * 0.55;
            }break;
        }
        return 0;
    },
    _openCpnInWindow:function(type){
        var profile = getDefaultProfileByType(type);
        profile.x = 100;
        profile.y = 100;
        profile.widget = $.extend(true,{},this.cpns[type].saveConfig());   // change by Jacye. deep copy.
        if (type == 3) {//qt
            profile.widget.detail = true;
            profile.widget.showTab = true;
        }
        if (type == 2) {//new
            profile.widget.isShowContent = true;
        }
        var self = this;
        setTimeout(function(){
//          var ticker;
//          if(self.performanceId&&self.performanceId.length>0){
//              ticker=self.performanceId;
//          }else{
//              if(self.ticker&&self.ticker.length>0){
//                  ticker=self.ticker;
//              }else{
//                  return;
//              }           
//          }
            if (type == 2) {
                workspaceManager.addWidgetToCurrentWs(type, "", profile);
            }else {
                workspaceManager.addWidgetToCurrentWs(type, self.ticker, profile);
            }
        },200);
    },
    _changeCpnOutSize:function(type){
        var w = 0;
        var h = 0;
        switch (type) {
            case 1:
                w = this.widthCol1;
                h = this._getBoxHeight(1); //chart
                break;
            case 3:
                w = this.widthCol1;
                h = this._getBoxHeight(2); //qt
                break;
            case 2:
                w = this.widthCol2;
                h = this._getBoxHeight(4); //news
                break;
            case 6:
                w = this.widthCol2;
                h = this._getBoxHeight(3); //L2
                break;
            case 7:
                w = this.widthCol2;
                h = this._getBoxHeight(3); //TS
                break;
            case 10:
                w = this.widthCol2;
                h = this._getBoxHeight(3); //Quote
                break;
        }
        if (w > 0 && h > 0 && this.cpns[type] && this.cpns[type].changeOutSize) {
            this.cpns[type].changeOutSize(w, h);
        }
    },
    changeOutSize:function(w, h){
        this.height = h;
        this.width = w - 10;
        this.widthCol1 = this.width < 900 ? this.width * 0.5 : this.width - 450;//this.width*0.6;
        this.widthCol2 = this.width < 900 ? this.width * 0.5 : 450;//this.width*0.4;
        this.coll.width(this.widthCol1);
        this.colr.width(this.widthCol2);
        this.el.css({width:w, height:h});
        this.el.children('.container').css({width:w, height:h});
        //this.el.find('.l-col, .r-col').css({height:h-14});
        
        try {
            this.box3Tab.setPanelOutSize('100%', this._getBoxHeight(3)); 
            this._changeCpnOutSize(1);
            this._changeCpnOutSize(3);
            this._changeCpnOutSize(2);
            this._changeCpnOutSize(6);
            this._changeCpnOutSize(7);
            this._changeCpnOutSize(10);
        }catch(e){
            //console.log(e)
        }
    },
    addTicker:function(Ticker){ //'XXX:IBM'
        var self = this;
        this.tValidation.checkTickers(Ticker,function(o){
            self.validateCallback(o)
        });
    },
    validateCallback:function(gkeyList){
        var k = gkeyList[0]
        if(typeof(this.hideLoading) == 'function'&&typeof(gkeyList)!= 'undefined'&&gkeyList.length==0){
            this.hideLoading();
        }
        if (k) {
            var d = gData[k] ? gData[k] : gData[gIdMap[k]];
            if (this.ticker && (this.ticker == k || this.performanceId == d.performanceId)) {
                return;
            }
            if (this.ticker) {
                this.tValidation.unSubscribe([this.ticker]); // unsubscribe ticker
            }
            if (this.setTitle) {
                this.setTitle('Security Research:',d.ticker);
            }
            this.ticker = d.exch + ':' + d.ticker;
            this.performanceId = d.performanceId;
             this.secId = d.secId;
            if (this.secType != d.mType) {
                this.secType = d.mType;
                this._createBox3(this.secType);
            }
            
            for(var c in this.cpns){
                this.cpns[c].acceptTicker(this.performanceId);
            }           
        }
    },
    fileMenuCallback:function(v){
        if(this.ticker==null||this.ticker==""){
            Util.message(QS_Lang.text["qtidrticker"]);
            return;
        }
        var id = this.performanceId;
        var type = this.secType.toUpperCase();
        if(type=="XI"){
            Util.message(QS_Lang.text["qtidrnotsupportindex"]);
            return;
        }
        if(type=="FO"||type=="FE"||type=="FC"){
            id = this.secId;
        }
        SiteBuilder_firstLoadLoginPage();
        var self = this;
        if (STATIC_VAR.marketIndexSessionExists == false) {
            this.interval = setInterval(function(){
                if (self.i < 10) {
                    self.i++;
                    if(STATIC_VAR.marketIndexSessionExists ==true){
                        window.open("https://awrd.morningstar.com/SB/Data/GetIDRDetailReport.aspx?disclosure=10&universe=10&datasrc=AWD&stkprem=1&instid=SBDEMO&lang=en-US&tool=Screener&symbol="+id,"","toolbar=no, menubar=no, resizable=no,location=no, status=no");
                        clearInterval(self.interval);
                    }
                } else {
                    clearInterval(self.interval);
                }
            }, 1000);
        }else{
            window.open("https://awrd.morningstar.com/SB/Data/GetIDRDetailReport.aspx?disclosure=10&universe=10&datasrc=AWD&stkprem=1&instid=SBDEMO&lang=en-US&tool=Screener&symbol="+id,"","toolbar=no, menubar=no, resizable=no,location=no, status=no");
        }
    },
    acceptTicker: function(Ticker){
        this.addTicker(Ticker);
    },
//    initAutoComplete:function(){
//        var idstr = (this.id<0)?'tmp_'+Math.abs(this.id):Math.abs(this.id);
//        var autoBoxID = 'autocpipt_'+idstr;
//        var downlistID = 'autocpddl_'+idstr
//        ////var callback = "push.proxy.getL2MarketDepth(" + this.id + ").autoCPCallback";
//        this.el.find('.ipt_symbol').attr('id', autoBoxID);
//        this.el.find('.autocp_ddl').attr('id', downlistID);
//        if ($("#"+autoBoxID).length < 1) {
//            return;
//        }
//        //Util.createAutoCompleteBox(autoBoxID,downlistID,"USA","EN-US",8,true,callback);
//    },
    autoCPCallback:function(o){
        this.addTicker(o);
    },
    saveConfig:function(){
        var cpnConfig = {};
        for (var k in this.cpns) {
            cpnConfig[k] = this.cpns[k].saveConfig();
        }
        return { ticker: this.performanceId||this.ticker, title: this.getTitle(), cpnConfig:cpnConfig, lock:this.lock }
    },
    clear:function(){
        for (var c in this.cpns) {
            if (this.cpns[c].isInit) {
                push.proxy.unregister(this.cpns[c]);
            }
            if (this.cpns[c].clear) {
                this.cpns[c].clear();
            }
        }
        //this.tValidation.unSubscribe([this.ticker.gkey]);  // unsubscribe ticker.
        for(var p in this){
            if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
        }
        // clear "clear" ?
    }
};